const func = {}

// typeOf, return 'array', 'object', 'function', 'null', 'undefined', 'string', 'number'
func.typeOf  = input => {
    return ({}).toString.call(input).slice(8, -1).toLowerCase()
}

// 合并对象属性（在原始对象上进行修改）
func.merge = (obj, options) => {
    if (obj && options) {
        for (let p in options) {
            if (func.typeOf(obj[p]) === 'object' && func.typeOf(options[p]) === 'object') {
                func.merge(obj[p], options[p])
            } else {
                obj[p] = options[p]
            }
        }
    }
    return obj
}


/**
 * 判断变量是否空值
 * undefined, null, '', false, 0, [], {} 均返回true，否则返回false
 */
func.isEmpty = (v) => {
    switch (typeof v) {
        case 'undefined' :
            return true;
        case 'string'    :
            if (v.trim().length === 0) return true;
            break;
        case 'boolean'   :
            if (!v) return true;
            break;
        case 'number'    :
            if (0 === v) return true;
            break;
        case 'object'    :
            if (null === v) return true;
            if (undefined !== v.length && v.length === 0) return true;
            for (const k in v) {
                return false;
            }
            return true;
        default:
            return false
    }
}
// 是否是json 字符串
func.isJsonStr  = (str) => {
    if (typeof str === 'string') {
        try {
            JSON.parse(str);
            return true;
        } catch (e) {
            return false;
        }
    }
}
// 防抖
func._debounce=(fn, delay)=>{
    delay = delay || 200;
    let timer;
    return function () {
        var th = this;
        var args = arguments;
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(function () {
            timer = null;
            fn.apply(th, args);
        }, delay);
    };
}
// 节流
func._throttle=(fn, interval)=>{
    let last;
    let timer;
    interval = interval || 200;
    return function () {
        var th = this;
        var args = arguments;
        var now = +new Date();
        if (last && now - last < interval) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                last = now;
                fn.apply(th, args);
            }, interval);
        } else {
            last = now;
            fn.apply(th, args);
        }
    }
}


export default func
